<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template #left>总记录条数：{{ total }}条</template>
        <el-button
          v-check="'POINT-USER-IMPORT'"
          size="small"
          type="success"
          @click="$router.push('/import?type=employee')"
        >
          导入
        </el-button>
        <el-button
          v-check="'POINT-USER-EXPORT'"
          size="small"
          type="warning"
          @click="exportExcel"
        >
          导出
        </el-button>
        <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
      </PageTools>
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            type="index"
            :index="indexMethod"
            width="100"
            align="center"
          />
          <el-table-column label="姓名" prop="username" align="center" />
          <el-table-column label="头像" align="center">
            <template v-slot="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                width="80"
                height="80"
                :src="row.staffPhoto"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" align="center" />
          <!-- <el-table-column
            label="聘用形式"
            align="center"
          >
            <template v-slot="{row}">
              {{ row.formOfEmployment === 1 ? '正式': '非正式' }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="聘用形式"
            align="center"
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" prop="departmentName" align="center" />
          <el-table-column label="入职时间" align="center">
            <template v-slot="{row}">
              {{ row.timeOfEntry | time }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" align="center">
            <template v-slot="{row}">
              {{ row.enableState === 1 ? '可用': '禁用' }}
              <!-- <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              /> -->
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assign(row.id)">角色</el-button>
              <el-button
                v-check="'POINT-USER-DELETE'"
                type="text"
                size="small"
                @click="del(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row type="flex" justify="end" style="margin-top: 20px;">
          <el-pagination
            layout="prev, pager, next, jumper"
            :total="total"
            background
            :page-size="size"
            :current-page="page"
            @current-change="changeFn"
          />
        </el-row>
      </el-card>
      <AddEmployee
        :show-dialog.sync="showDialog"
        @getEmployeeList="getEmployeeList"
      />
      <el-dialog title="二维码" :visible.sync="showCodeDialog" @opened="showQrCode" @close="imgUrl=''">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './components/AssignRole.vue'
import QrCode from 'qrcode'
import { delEmployee, getEmployeeList } from '@/api/employees'
import employeeEnum from '@/api/constant/employees'
import AddEmployee from './components/AddEmployee'
import moment from 'moment'
// import { export_json_to_excel } from '@/utils/Export2Excel'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      // 存储员工信息
      list: [],
      // 存储总数量
      total: 0,
      // 当前页
      page: 1,
      // 每页的条数
      size: 5,
      loading: false,
      hireType: employeeEnum.hireType,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page, this.size)
      this.list = rows
      this.total = total
      this.loading = false
    },
    changeFn(value) {
      this.page = value
      // 重新发送请求
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      if (cellValue === null) {
        return '其他'
      }
      return this.hireType.find(item => item.id === +cellValue).value
    },
    async del(id) {
      try {
        await this.$confirm('你确定要删除吗', '温馨提示', { type: 'warning' })
      } catch {
        return
      }
      // 发送请求删除
      await delEmployee(id)
      // 提示消息
      this.$message.success('删除员工成功')
      // 重新渲染
      this.getEmployeeList()
    },
    /*
      核心思路：
        1. 需要用到一个方法 Export2Excel 文件中的export_json_to_excel
        注意：为了性能优化，这里使用的是异步的导入
    */
    async exportExcel() {
      const excel = await import('@/utils/Export2Excel')
      // 发送ajax请求，获取所有员工的数据
      const { rows } = await getEmployeeList(1, 1000)
      const userRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const multiHeader = [
        ['姓名', '主要信息', '', '', '', '', '部门']
      ]
      const header = Object.keys(userRelations)
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']

      // [''入职日期', '手机号', '姓名']
      const data = []
      rows.forEach(item => {
        const arr = []
        header.forEach(h => {
          // 额外判断
          if (h === '入职日期' || h === '转正日期') {
            // 只想要年月日
            let time = item[userRelations[h]]
            if (time) {
              time = moment(item[userRelations[h]]).format('YYYY-MM-DD')
            }
            arr.push(time)
          } else if (h === '聘用形式') {
            console.log(item[userRelations[h]])
            const result = employeeEnum.hireType.find(v => v.id === +item[userRelations[h]])
            arr.push(result ? result.value : '其他')
          } else {
            arr.push(item[userRelations[h]])
          }
        })
        data.push(arr)
      })
      excel.export_json_to_excel({
        header,
        multiHeader,
        // 配置合并
        merges,
        data,
        filename: '员工数据',
        bookType: 'xlsx'
      })
    },
    showQrCode(url) {
      console.log(url, '123')
      // url存在的情况下 才弹出层
      if (!url) return
      this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
      // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
      this.$nextTick(() => {
        // 此时可以确认已经有ref对象了
        QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
        // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
      })
    },
    assign(id) {
      this.userId = id
      this.showRoleDialog = true
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    }
    // check(point) {
    //   const points = this.$store.state.user.userInfo.roles.points
    //   return points.some(item => item.toLowerCase() === point.toLowerCase())
    // }
  }
}
</script>

<style>

</style>
